package com.chentf.nio.c3;

import com.chentf.nio.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 * @author chentengfei
 * @desc 阻塞模式下服务端
 * @date 2022-05-07 15:34:51
 */
public class Server01 {

    public static void main(String[] args) {
        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        //获取服务器通道
        try (ServerSocketChannel ssc = ServerSocketChannel.open()){
            //为通道绑定端口
            ssc.bind(new InetSocketAddress(8085));
            //用户存放连接的集合
            ArrayList<SocketChannel> channels = new ArrayList<>();
            //循环接收连接
            while (true){
                System.out.println("before connecting...");
                //没有连接时,会阻塞线程,accept 建立与客户端连接， SocketChannel 用来与客户端之间通信
                SocketChannel socketChannel = ssc.accept(); //阻塞方法,线程停止运行
                System.out.println("after connecting...");
                channels.add(socketChannel); //将连接存放到集合中
                //循环遍历集合中的连接
                for(SocketChannel channel : channels){
                    System.out.println("before reading...");
                    //处理通道中的数据,如果数据可读时,会阻塞线程
                    channel.read(byteBuffer);
                    byteBuffer.flip(); //切换读写模式
                    ByteBufferUtil.debugRead(byteBuffer); //打印数据
                    byteBuffer.clear();
                    System.out.println("after reading...");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
